﻿module Sustainalytics.Common {

    import Authentication = Sustainalytics.Authentication;


    var mod = angular.module(commonModuleName);

    mod.factory('staticObjects', ['$rootScope', 'notificationFactory', '$location', ($rootScope, notificationFactory, $location) => {
        var getMessageByInternalCode = internalCode => {
            var message = "";
            switch (internalCode) {
                case 1000:
                    message = "Another report already generating.";
                    break;
                case 1001:
                    message = "Generating the report failed - Please contact your Administrator";
                    break;
                case 1002:
                    message = "Total number of concurrent users per application reached!";
                    break;
                case 1003:
                    message = "Login failed";
                    break;
                case 1004:
                    message = "The combination of username and password is incorrect. Please check and try again.";
                    break;
                case 1005:
                    message = "Please enter a valid email address.";
                    break;
                case 1006:
                    message = 'Your account is currently inactive, please <a href="mailto:client@sustainalytics.com">contact us</a> if you would like to regain access.';
                    break;
                case 1007:
                    message = "Your password expired, an email will be sent with instructions to change your password. Please contact your account manager, if you don’t receive an email within 15 minutes.";
                    break;
                case 1008:
                    message = "The temporary key has expired. Please use the forgot password link to create a new one.";
                    break;
                case 1009:
                    message = "The temporary key is no longer valid.";
                    break;
                case 1010:
                    message = "There was a critical error processing your request. The platform administrators have been notified.";
                    break;
                case 1011:
                    message = "There was a critical error processing your request. The platform administrators have been notified.";
                    break;
                case 1012:
                    message = "There was an error changing your password. Please try again later.";
                    break;
                case 1019:
                    message = "There was a critical error processing your request. The platform administrators have been notified.";
                    break;

                case 9999:
                    message = "You are not authorized to use that resource.";
                    break;

                default:
                    message = "An error has occurred. Please contact your administrator!";
                    break;
            }
            return message;
        };

        var staticObjects: IStaticObjects = {
            getMessageByInternalCode: getMessageByInternalCode,
            reportTypes: [{ id: 1, name: "Company Report" }, { id: 2, name: "Relative Analysis Report" }],
            companies: [{ id: "7bafdbd0-2e9c-4048-8a85-000bbf41af01", name: "Default" }],
            comparativeGroups: [{ id: 1, name: "Peer Group" }, { id: 2, name: "Industry Group" }],
            matrixes: [{ id: "9c19a43d-a9f6-49f1-8452-061f32d0f6fc", name: "Default Matrix" }],
            referenceUniverses:
            [
                { id: "9c19a43d-a9f6-49f1-8452-061f32d0f6fc", name: "Reference Universe 1" },
                { id: "b8cc3ca4-045b-4987-b1ee-402f7a058c14", name: "Reference Universe 2" },
                { id: "0bcc0578-520b-4a72-93c6-a863c2d2321f", name: "Reference Universe 3" }
            ],
            apiBaseUrl: "/reports/api/",
            authBaseUrl: "/security",
            screeningToolBaseUrl: "/screening",
            screeningToolServBaseUrl: "/screeningtoolserv/api/v1",
            resourcePermissions: "",
            portfolioBaseUrl: "/portfolioserv",
            reportResponse: { Status: "", Finished: "", FilePath: "", Created: "", Error: "", ReportType: "" },
            reportResponseBroadcast: reportNotification => {
                staticObjects.reportResponse = reportNotification;
                $rootScope.$broadcast('handleBroadcast');
            },
            getGCCSAssesmentByValue: (value: number) => {
                switch (value) {
                    case 0:
                        return "Compliant";
                    case 1:
                        return "Watchlist";
                    case 2:
                        return "Non-Compliant";
                    default:
                        return "";
                }
            },
            broadcastItem: () => {
                $rootScope.$broadcast('handleBroadcast');
            },


            getErrorMesageByStatusCode: (statusCode, data) => {
                var message = "";
                switch (statusCode) {
                    case 401:
                        message = "Unauthorized";
                        break;
                    case 500:
                        if (data && data.code) { message = getMessageByInternalCode(data.code); }
                        else {
                            message = "An error has occurred. Please contact your administrator!";
                        }
                        break;
                    case 404:
                        message = "Resource not found";
                        break;
                    case 400:
                        message = "Bad request. Resource not found";
                        break;
                    case 2200:
                        message = "File is not *.xls or *.xlsx";
                        break;

                    // Filter errors
                    case 4001:
                        message = "A filter by this name already exists, please enter a unique name and press save.";
                        break;
                    case 4002:
                        message = "A filter by this name already exists, please enter a unique name and press save.";
                        break;
                    case 4003:
                        message = "A filter name must be provided before pressing save.";
                        break;
                    case 4004:
                        message = "A filter name cannot be the save as a Standard Filter.";
                        break;
                    // Portfolio errors
                    case 5001:
                        message = "Portfolio is null";
                        break;
                    case 5002:
                        message = "Portfolio id is null!";
                        break;
                    case 5003:
                        message = "You are not authorise to change the status of the portfolio!";
                        break;
                    case 5004:
                        message = "You are not authorise to delete the portfolio!";
                        break;
                    case 5005:
                        message = "Portfolio is null!";
                        break;
                    case 5006:
                        message = "Portfolio is not correct!";
                        break;
                    case 5007:
                        message = "Portfolio is not correct!";
                        break;
                    case 5008:
                        message = "You are not authorise to rename the portfolio!";
                        break;
                    case 5009:
                        message = "This portfolio name already exists, please enter a unique name and try again!";
                        break;
                    case 5010:
                        message = "Portfolio name is null!";
                        break;
                    case 5011:
                        message = "Portfolio is no longer shared within the account!";
                        break;
                    case 5012:
                        message = "UserId claim is null!";
                        break;
                    case 5013:
                        message = "AccountId claim is null!";
                        break;
                    case 5014:
                        message = "You are not authorise!";
                        break;
                    case 5015:
                        message = "Portfolio is no longer available!";
                        break;
                    //case 5103:
                    //    message = "The company is in the selected portfolio!";
                    //    break;
                    // end Portfolio errors
                    case 5104:
                        message = "You are not authorise to add company to portfolio!";
                        break;
                    //Portfolio securities
                    case 5200:
                        message = "The path is incorect!";
                        break;
                    case 5201:
                        message = "There are securities that don't corespond with companies!";
                        break;
                    case 5202:
                        message = "Selected file structure not valid. Please select a file with identical structure as the downloaded template format."
                        break;
                    case 5203:
                        message = "Select a file for upload!";
                        break;
                    case 5210:
                        message = "Please upload a valid file format (.xls or .xlsx)";
                        break;
                    // Company errors
                    case 6014:
                        message = "You do not have the necessary rights to access this page. Please contact your account manager for details.";
                        break;
                    // end Company errors
                    default:
                        message = "Unknown error";
                        break;
                }
                return message;
            },
            errorCallback: (error, status, internalCode) => {
                if (error != "") {
                    notificationFactory.error(error.exceptionMessage, error.message);
                } else {
                    notificationFactory.error("", staticObjects.getErrorMesageByStatusCode(status, internalCode));
                }
            },
            initSignalR: () => {
                if ($rootScope.authData && $rootScope.authData.access_token) {
                    $.connection.hub.qs = { "access_token": $rootScope.authData.access_token };
                    $.connection.hub.start()
                        .done(() => {
                        })
                        .fail(error => {
                            //alert(error.message);
                            notificationFactory.error("SignalR failed to initialize!\n" + error.message, "SignalR error");
                        });
                }
            },
            reportStatus: {
                Requested: 'Requested',
                Running: 'Running',
                Finished: 'Finished',
                Failed: 'Failed',
            },
            clearUserInfo: () => {
                $rootScope.userInfo = new UserInfoClass();
                var authData: Authentication.AuthData = { expires_in: null, access_token: null, refresh_token: null, loginTime: null };
                $rootScope.authData = authData;
            },
            redirectToLogin: () => {
                if ($location.path() != '/login') {
                    $location.url('/login');
                    //if (!$rootScope.$$phase) { $rootScope.$apply(); }
                }
            },
            redirectToDefault: (redirectTo?: string) => {
                if (redirectTo) {
                    $location.url(redirectTo);
                }
                else {
                    if ($location.path() != '/') {
                        $location.url('/');
                        //if (!$rootScope.$$phase) { $rootScope.$apply(); }
                    }
                }
            },
            redirectToLink: (link) => {
                if ($location.path() != link) {
                    $location.url(link);
                }
            },
            authDataIsExpired: (authData: Authentication.AuthData) => {
                if (!authData.loginTime) {
                    return true;
                }
                var day = authData.loginTime.getDay();
                var month = authData.loginTime.getMonth();
                var year = authData.loginTime.getFullYear();
                var hours = authData.loginTime.getHours();
                var minutes = authData.loginTime.getMinutes();
                var seconds = authData.loginTime.getSeconds();

                var endDate = new Date(year, month, day, hours, minutes, seconds + authData.expires_in);////
                var now = new Date();

                if (endDate > now) {
                    return true;
                } else {
                    return false;
                }
            },
            eventsServiceBaseUrl: "/eventsserv",
            screeningExportDetails: null
        };
        return staticObjects;
    }]);
}